package com.blast.comicsisland.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.blast.comicsisland.R;
import com.blast.comicsisland.activity.CommicActivity;
import com.blast.comicsisland.adapters.RecommendPagerAdapter;
import com.blast.comicsisland.adapters.WaterFallAdapter;
import com.blast.comicsisland.model.recommend.recommendbody.ComicsList;
import com.blast.comicsisland.model.recommend.recommendhead.AdListJson;
import com.blast.comicsisland.utils.JsonUtils;

import com.blast.comicsisland.utils.SpaceItemDecoration;

import kale.layoutmanager.ExStaggeredGridLayoutManager;
import kale.recycler.ExCommonRcvAdapter;
import kale.recycler.ExRecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

/**
 * 为BookStroeFragment的子Fragment 推荐
 * 上方为自动滚动ViewPager 与TextView 二者帧布局 TextView在上层
 * 下方为瀑布流展示选项条目
 */
public class RecommendFragment extends Fragment implements AdapterView.OnItemClickListener {
    private String waterfallUrl = "http://mhjk.1391.com/comic/comicslist_v2_sb?e=";
    private ExRecyclerView recyclerView;
    private String pageno="1";
    private List<ComicsList> comics;
    private ExStaggeredGridLayoutManager manager;
    private ExCommonRcvAdapter adapter;
    private AutoScrollViewPager autoScrollViewPager;
    private List<AdvertFragment> fragments;
    private RecommendPagerAdapter pagerAdapter;
    private View pagerView;
    private MyAsyncTask myAsyncTask;
    private AdHeaderLoader adHeaderLoader;
    private View thisView;

    public RecommendFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_recommend, container, false);
        thisView = view;
        recyclerView = (ExRecyclerView)view.findViewById(R.id.bookstore_recyclerview);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setItemAnimator(null);
        //设置item边距
        recyclerView.addItemDecoration(new SpaceItemDecoration(20));

        // autoScrollViewPager.setOnPageChangeListener(this);
        //RecyclerView布局管理器为网格瀑布流布局 两列



        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //===============================
        recyclerView.setLayoutManager(null);
        recyclerView=null;
        autoScrollViewPager=null;
        adapter=null;
        pagerAdapter=null;
        manager=null;
        pagerView = null;
        pageno="1";
        fragments=null;
        comics=null;

        recyclerView = (ExRecyclerView)thisView.findViewById(R.id.bookstore_recyclerview);
        //===================================
        //TODO 初始化设置autoScrollViewPager
        manager = new ExStaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        pagerView = LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_header,recyclerView,false);
        autoScrollViewPager = (AutoScrollViewPager) pagerView.findViewById(R.id.header_viewpager);
        fragments = new ArrayList<>();
        comics = new ArrayList<>();
        //保持固定大小 用于优化
        recyclerView.setHasFixedSize(true);
        pagerAdapter = new RecommendPagerAdapter(getFragmentManager(),fragments);
        autoScrollViewPager.setOffscreenPageLimit(5);
        autoScrollViewPager.setInterval(6000);
        autoScrollViewPager.setStopScrollWhenTouch(false);
        autoScrollViewPager.startAutoScroll();
        autoScrollViewPager.setAdapter(pagerAdapter);
        recyclerView.addHeaderView(pagerView);
        //添加至RecyclerView的头部



        //TODO 初始化适配器 comics 应在异步任务中获取 然后notify

        adapter = new WaterFallAdapter(comics,getActivity());
        recyclerView.setAdapter(adapter);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            /**
             * 只能设置内部类 当页面滚动时回调该方法
             *
             * @param recyclerView
             * @param newState
             */
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //判断滑动到底部进行加载操作
                //获取布局文件在屏幕上最后可见的item的点
                //因为是两列瀑布流 返回的值为数组,长度为2
                int[] lastVisibleItemPositions = manager.findLastVisibleItemPositions(null);
                //如果最后一个item的positions为list的最后一个position
                if (lastVisibleItemPositions[1]== comics.size()-1||lastVisibleItemPositions[0]==comics.size()-1){
                    //TODO 执行加载操作
                   myAsyncTask = new MyAsyncTask();
                    myAsyncTask.execute();
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        adHeaderLoader = new AdHeaderLoader();
        adHeaderLoader.execute();
        myAsyncTask = new MyAsyncTask();
        myAsyncTask.execute();
    }


    @Override
    public void onStop() {
        super.onStop();
        myAsyncTask.cancel(true);
        //adHeaderLoader.cancel(true);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        ComicsList comicsList = comics.get(position);
        Intent intent = new Intent(getActivity(), CommicActivity.class);
        String bigBookId = comicsList.getBigbookId();
        intent.putExtra("bigBookId", bigBookId);
        startActivity(intent);
    }


    public class MyAsyncTask extends AsyncTask<Void,Void,List<ComicsList>> {
        @Override
        protected List<ComicsList> doInBackground(Void... params) {
            String path = "{\"type\":\"1\",\"pageno\":\""+pageno+"\",\"pagesize\":\"10\"}";

            List<ComicsList> comicsLists = null;
            String s = JsonUtils.doPostRequest(waterfallUrl + (System.currentTimeMillis() / 1000), path);
            pageno=Integer.toString(Integer.parseInt(pageno) + 1);
            //====================test parsejson===================
            if (s!=null) {
                try {
                    JSONObject object = new JSONObject(s);
                    JSONObject infoObject = object.getJSONObject("info");
                    JSONArray comicsListArray = infoObject.getJSONArray("comicsList");
                    comicsLists = new ArrayList<>();
                    for (int i = 0; i < comicsListArray.length(); i++) {
                        JSONObject comicObject = comicsListArray.getJSONObject(i);
                        String subjectName = comicObject.getString("subject_name");
                        String progresstype = comicObject.getString("progresstype");
                        String bigbookName = comicObject.getString("bigbook_name");
                        String bigbookId = comicObject.getString("bigbook_id");
                        String keyName = comicObject.optString("key_name");
                        String bigbookAuthor = comicObject.getString("bigbook_author");
                        String bigbookview = comicObject.getString("bigbookview");
                        String coverurl = comicObject.getString("coverurl");
                        ComicsList comic1 = new ComicsList();
                        comic1.setBigbookAuthor(bigbookAuthor);
                        comic1.setBigbookId(bigbookId);
                        comic1.setBigbookName(bigbookName);
                        comic1.setBigbookview(bigbookview);
                        comic1.setCoverurl(coverurl);
                        comic1.setKeyName(keyName);
                        comic1.setProgresstype(progresstype);
                        comic1.setSubjectName(subjectName);
                        comicsLists.add(comic1);
                    }
                    int size = comicsLists.size();
                    //Log.d("tag", "size:" + comicsLists.size() + "item1:" + comicsLists.get(0).getCoverurl());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            //=====================================================

            return comicsLists;
        }


        @Override
        protected void onPostExecute(List<ComicsList> comicsLists) {
            if (comicsLists!=null) {
                comics.addAll(comicsLists);
                adapter.updateData(comics);
            }
        }
    }



    public class AdHeaderLoader extends AsyncTask<Void,Void,List<AdvertFragment>>{

        @Override
        protected List<AdvertFragment> doInBackground(Void... params) {
            //.d("ExecuteCount","execute");
            String path = "http://mhjk.1391.com/comic/getproad?adgroupid=9&e="+(System.currentTimeMillis()/1000)+"&platformtype=1&channelid=baidu";
            String s = JsonUtils.doGetRequest(path);
            String str = JsonUtils.stringToRegex(s);

            List<AdvertFragment> fragmentList =null;
            //====================test parsejson===================
            if (s!=null) {
                try {
                    JSONObject object = new JSONObject(str);
                    JSONObject info = object.getJSONObject("info");
                    JSONArray adListArray = info.getJSONArray("adlistjson");
                    fragmentList = new ArrayList<>();
                    for (int i=0;i<adListArray.length();i++){
                        JSONObject adListObject = adListArray.getJSONObject(i);

                        String id = adListObject.getString("id");

                        String imageurl = adListObject.getString("imageurl");

                        String title = adListObject.getString("title");

                        AdvertFragment fragment = new AdvertFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("imageurl",imageurl);
                        bundle.putString("title",title);
                        bundle.putString("id",id);
                        fragment.setArguments(bundle);
                        fragmentList.add(fragment);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            return fragmentList;
        }

        @Override
        protected void onPostExecute(List<AdvertFragment> fragmentList) {
           // Log.d("fragmentList is null?",""+(fragmentList==null)+" "+fragmentList.size());
            if (fragmentList!=null){
                //fragments.removeAll(fragments);
                //fragments.clear();
                fragments.addAll(fragmentList);
                pagerAdapter.notifyDataSetChanged();
            }
        }
    }
}
